package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"regexp"
)

type reg struct {
	todayCount, yesterdayCount, totalCount, lastLogin string
}

func main() {
	var key = [4]string{
		"https://my.oschina.net/u/3992938",
		"https://my.oschina.net/u/2376927",
		"https://my.oschina.net/tigerlovecat",
		"https://my.oschina.net/u/3754087",
	}

	for index := 0; index < len(key); index++ {
		ret, err := doHttpGetRequest(key[index])
		if err != nil {
			fmt.Println("network request error")
		} else {
			if index == 1 {
				//fmt.Println(ret)
			}
			fmt.Println(key[index])
			regResultText(ret)
		}
	}
}

func regResultText(text string) (resp reg) {

	// 正则匹配字段 todayCount
	todayCountReg := regexp.MustCompile(`今日访问：[\d]+`)
	todayCount := todayCountReg.FindAllString(text, -1)
	resp.todayCount = todayCount[0]
	fmt.Println(todayCount[0])
	// 正则匹配字段 yesterdayCount
	yesterdayCountReg := regexp.MustCompile(`昨日访问：[\d]+`)
	yesterdayCount := yesterdayCountReg.FindAllString(text, -1)
	resp.yesterdayCount = yesterdayCount[0]
	fmt.Println(yesterdayCount[0])
	// 正则匹配字段 totalCount
	totalCountReg := regexp.MustCompile(`所有访问：[\d]+`)
	totalCount := totalCountReg.FindAllString(text, -1)
	resp.totalCount = totalCount[0]
	fmt.Println(totalCount[0])
	// 正则匹配字段 lastLogin 最近登录
	lastLoginReg := regexp.MustCompile(`最近登录：(.*?)<+`)
	lastLogin := lastLoginReg.FindAllString(text, -1)
	lastLoginStr := lastLogin[0]
	resp.lastLogin = lastLoginStr[0 : len(lastLoginStr)-1]
	fmt.Println(lastLoginStr[0 : len(lastLoginStr)-1])

	return resp
}

/**	直接请求http 返回请求数据 */
func doHttpGetRequest(url string) (ret string, err error) {

	resp, err := http.Get(url)
	if err != nil {
		return "", err
	} else {
		// 用于 句柄关闭
		defer resp.Body.Close()
		// IO流数据读取 需要引入 io/ioutil
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return "", nil
		} else {
			return string(body), err
		}
	}
}
